import { useState, useEffect } from 'react';
import { message } from 'antd';
import { history } from 'umi';

import request from '@/utils/request';

const mergeUserInfo = (user, relatedBusinessObject) => {
    const rt = {
        ...user.currentUser,
        employeeCode: user.currentUser.employeeCode,
        id: relatedBusinessObject.id,
        // 试用期采用relatedBusinessObject的tryDuration, 防止从offer带过来的不规范数据引起错误
        tryDuration: relatedBusinessObject.tryDuration
    };
    Object.keys(relatedBusinessObject).forEach(key => {
        if (!rt[key]) {
            rt[key] = relatedBusinessObject[key];
        }
    });
    return rt;
};

/**
 * 获取转正详情
 * @param processTemplateId
 * @param processInstanceId
 * @param regularId
 * @returns {{loading: *, detail: *}}
 */
export const useDetail = ({ processTemplateId, processInstanceId, regularId, type, user }) => {
    const [loading, setLoading] = useState(false);
    const [detail, setDetail] = useState({
        processTaskInstances: [],
        userInfo: {},
        processTaskTemplates: [],
        relatedBusinessObject: {},
        currentProcessTaskInstance: {
            relatedBusinessObject: {}
        }
    });
    useEffect(() => {
        const getProcess = async () => {
            setLoading(true);
            let url = '/api/oa/v1/regular/personal/detail';
            if (type === 'company') {
                url = '/api/oa/v1/regular/detail';
            }
            const response = await request(url, {
                method: 'POST',
                data: {
                    processTemplateId,
                    processInstanceId,
                    regularId: (regularId && window.parseInt(regularId)) || ''
                }
            });
            if (response.code === 10000) {
                const { processInstance, relatedBusinessObject } = response.data;
                const userInfo = mergeUserInfo(user, relatedBusinessObject);
                if (regularId) {
                    setDetail(processInstance);
                } else {
                    setDetail({
                        processTaskInstances: [],
                        processTaskTemplates: processInstance.processTaskTemplates,
                        currentProcessTaskInstance: {
                            relatedBusinessObject: userInfo
                        }
                    });
                }
            } else {
                message.error(response.msg);
                history.push('/personal/message/system');
            }
            setLoading(false);
        };

        getProcess();
    }, []);

    return {
        loading,
        detail
    };
};
